package com.example.shopping_cart.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.Result;
import com.example.config.JwtConfig;
import com.example.shopping_cart.service.ShoppingCartService;
import com.example.shopping_cart_model.entity.ShoppingCart;
import com.example.user.service.UserService;
import com.example.user_model.entity.User;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author sjz
 * @since 2024-07-10
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Resource
    private ShoppingCartService shoppingCartService;

    @Resource
    private UserService userService;

    @Resource
    HttpServletRequest request;

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 查看购物车
     *
     * @return
     */
    @GetMapping("/list")
    public Result<List<ShoppingCart>> list() {
        log.info("查看购物车方法执行了...");
        String userId = this.getId();
        //根据当前用户的id查询数据库
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        queryWrapper.orderByDesc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        return Result.success(list);
    }

    /**
     * 添加到购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public Result<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        log.info("添加到购物车方法执行了...");
        log.info(shoppingCart.toString());
        String userId = this.getId();
        //用户点击加入购物车,设置当前用户id,才能知道当前是谁的购物车
        shoppingCart.setUserId(userId);
        //执行添加商品逻辑
        shoppingCart = shoppingCartService.addDish(shoppingCart);
        //将添加后的购物车返回
        return Result.success(shoppingCart);
    }


    /**
     * 减少购物车商品数量
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public Result<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        log.info(shoppingCart.toString());
        //用户点击减少按钮,设置当前用户id,才能知道当前要减少的是谁的购物车内容
        String userId = this.getId();
        shoppingCart.setUserId(userId);
        shoppingCart = shoppingCartService.subDish(shoppingCart);

        return Result.success(shoppingCart);
    }


    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public Result<String> clean() {
        //查询当前用户的购物车数据,删除数据
        //SQL:DELETE FROM shopping_cart WHERE (user_id = ?)
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, this.getId());

        shoppingCartService.remove(wrapper);

        return Result.success("清空购物车成功");
    }

    /**
     * 利用请求头中的手机号,获取用户id,给其他方法调用
     *
     * @return
     */
    public String getId() {
        //从redis缓存获取token
        String token = (String) redisTemplate.opsForValue().get("Authorization");
        //获取请求头中的token
        //String token = request.getHeader("Authorization").replace("\"", "");
        log.info("token:{}", token);
        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        //根据手机号查询当前用户
        String phone = claims.get("name", String.class);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userService.getOne(wrapper);
        //获取id
        return user.getId();
    }

}
